package com.zhentao.minio.service.impl;

import com.zhentao.minio.config.MinioConfig;
import com.zhentao.minio.config.MinioConfigProerties;
import com.zhentao.minio.service.FileStorageService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: MinioFileStorageServiceImpl
 * @Author: 振涛教育_Q
 * @Date: 2024/10/24 16:36
 */
@Slf4j
@EnableConfigurationProperties(MinioConfigProerties.class)
@Import(MinioConfig.class)
public class MinioFileStorageServiceImpl implements FileStorageService {
    @Autowired
    private MinioClient minioClient;  // minio客户端
    @Autowired
    private MinioConfigProerties minioConfigProerties;  // minio 必要参数
    private final static String separator = "/";  // 分隔符  用作路径分割


    // dirPath  目录路径   filename  文件名
    public String builderFilePath(String dirPath,String filename) {
        // 开辟字符串空间，大小为  50
        StringBuilder stringBuilder = new StringBuilder(50);
        // 目录文件不为空
        if(!StringUtils.isEmpty(dirPath)){
            // 在目录文件后 拼接一个  /
            stringBuilder.append(dirPath).append(separator);
        }
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String todayStr = sdf.format(new Date()); // 获取当前时间
        // 时间后拼接  /
        stringBuilder.append(todayStr).append(separator);
        // 拼接完时间之后   将文件名拼接到 后面
        stringBuilder.append(filename);
        // 最后返回
        return stringBuilder.toString();
    }

    @Override
    public String uploadImgFile(String prefix, String filename, InputStream inputStream) {
        // 传入文件路径前缀 可能是目录,第二个参数为文件名称
        String filePath = builderFilePath(prefix, filename);
        try {
            // 创建上传文件/图片对象
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)  // 生成的路径作为对象名
                    .contentType("image/jpg")  // 文本类型  img
                    .bucket(minioConfigProerties.getBucket()) // 获取桶名称
                    .stream(inputStream,inputStream.available(),-1)  // 读取文件，直到文件底部
                    .build(); // 构建
            minioClient.putObject(putObjectArgs);  // 将文件上传到minio

            StringBuilder urlPath = new StringBuilder(minioConfigProerties.getReadPath());
            urlPath.append(separator+minioConfigProerties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);
            //return urlPath.toString();

            //获取文件的访问路径
            String desPath = minioClient.getObjectUrl(minioConfigProerties.getBucket(),filename);
            return urlPath.toString();

        }catch (Exception ex){
            log.error("minio put file error.",ex);
            throw new RuntimeException("上传文件失败");
        }
    }

    @Override
    public String uploadHtmlFile(String prefix, String filename, InputStream inputStream) {
        String filePath = builderFilePath(prefix, filename);
        try {
            // 配置上传对象请求的类。它的主要作用是封装上传文件时所需的各种参数
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)
                    .contentType("text/html")
                    .bucket(minioConfigProerties.getBucket()).stream(inputStream,inputStream.available(),-1)
                    .build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(minioConfigProerties.getReadPath());
            urlPath.append(separator+minioConfigProerties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);
            return urlPath.toString();
        }catch (Exception ex){
            log.error("minio put file error.",ex);
            ex.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
    }

    @Override
    public void delete(String pathUrl) {
        String key = pathUrl.replace(minioConfigProerties.getEndpoint()+"/","");
        int index = key.indexOf(separator);
        String bucket = key.substring(0,index);
        String filePath = key.substring(index+1);
        // 删除Objects
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();
        try {
            minioClient.removeObject(removeObjectArgs);
        } catch (Exception e) {
            log.error("minio remove file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();
        }
    }

    @Override
    public byte[] downloadFile(String pathUrl) {
        String key = pathUrl.replace(minioConfigProerties.getEndpoint()+"/","");
        int index = key.indexOf(separator);
        String bucket = key.substring(0,index);
        String filePath = key.substring(index+1);
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minioConfigProerties.getBucket()).object(filePath).build());
        } catch (Exception e) {
            log.error("minio down file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
}
